package logic

import (
	"context"
	"fmt"
	"good/model/mysql"
	"good/model/redis"
	"gorm.io/gorm"

	"good/goodrpc/goodrpc"
	"good/goodrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodUpdateLogic {
	return &GoodUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodUpdateLogic) GoodUpdate(in *goodrpc.GoodUpdateRequest) (*goodrpc.GoodUpdateResponse, error) {
	// todo: add your logic here and delete this line

	get := redis.Client.Get("sendSmsUpdate" + in.Phone)
	if get.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("验证码输入错误,请重新输入")
	}
	var good mysql.Good
	mysql.DB.Debug().Where("name = ?", in.Name).Find(&good)
	if good.ID == 0 {
		return nil, fmt.Errorf("该供应商不存在")
	}
	update := mysql.Good{
		Model:  gorm.Model{ID: good.ID},
		Name:   in.Name,
		Cost:   float64(in.Cost),
		Market: float64(in.Market),
		Group:  float64(in.Group),
	}
	err := mysql.DB.Debug().Updates(&update).Error
	if err != nil {
		return nil, fmt.Errorf("商品修改失败")
	}
	redis.Client.Del("sendSmsUpdate" + in.Phone)
	return &goodrpc.GoodUpdateResponse{Id: int64(update.ID)}, nil
}
